<?php

/*
 * Google sitemap
 *
 */
if ($path[0] == 'sitemap.xml') {
	$smarty->assign('sitemap', googleSitemap(array(), 0, '/'));
	header("Content-type: text/xml");
	$smarty->display("{$app_root}/admin/frontend/sitemap.tpl.xml");
	exit;
}
function googleSitemap($sitemap, $pid, $path) {
	global $db, $site;
	$pages = $db->fetchAll("SELECT p.id, r.path, r.published FROM site_pages p LEFT JOIN site_pages_revisions r ON p.revision_id=r.id WHERE site_id=? AND parent_id=? AND active=1", array($site['id'], $pid));
	foreach($pages as $page) {
		$page['priority'] = '1.0';
		
		array_push($sitemap, array(	'loc' => 'http://' . $_SERVER['SERVER_NAME'] . str_replace('//', '/', $path . $page['path'] . "/"),
									'lastmod' => substr($page['published'], 0, 10),
									'priority' => $page['priority']
								));
		$sitemap = googleSitemap($sitemap, $page['id'], $path . $page['path'] . '/');
	}
	return $sitemap;
}

/*
 * Process the path, and populate $page and $breadcrumb
 *
 */
$parent_id = 0;
$path[-1] = ''; asort($path);
if (!$path[0]) { unset($path[0]); }
$base_path = '';
$breadcrumb = array();

if (isset($_REQUEST['revision_id'])) {
	$page_sql = "SELECT p.id, r.id AS revision_id, p.parent_id, r.title, r.path, r.link, r.meta_description, r.meta_keywords, r.template_id, r.published, (SELECT COUNT(*) FROM site_pages_revisions_plugins WHERE revision_id=r.id AND manage_path=1) AS plugin_manages_path, o.module_name FROM site_pages p LEFT JOIN site_pages_revisions r ON r.id=(SELECT MAX(id) FROM site_pages_revisions maxr WHERE maxr.page_id=p.id) LEFT JOIN cms_overrides o ON p.id=o.page_id WHERE p.site_id=? AND r.path=? AND p.parent_id=? AND p.id=r.page_id";
} else {
	$page_sql = "SELECT p.id, p.revision_id, p.parent_id, r.title, r.path, r.link, r.meta_description, r.meta_keywords, r.template_id, r.published, (SELECT COUNT(*) FROM site_pages_revisions_plugins WHERE revision_id=r.id AND manage_path=1) AS plugin_manages_path, o.module_name FROM site_pages p LEFT JOIN site_pages_revisions r ON p.revision_id=r.id LEFT JOIN cms_overrides o ON p.id=o.page_id WHERE p.site_id=? AND r.path=? AND p.parent_id=? AND active=1";
}
for($i=-1;$i<count($path)-1;$i++) {
	$this_page = $db->fetchRow($page_sql, array($site['id'], $path[$i], $parent_id));
	if (!$this_page) {
		break;
	}
	$this_page['full_path'] = str_replace('//', '/', $base_path . '/' . $this_page['path']);
	$parent_id = $this_page['id'];
	$breadcrumb[] = $this_page;
	if ($this_page['plugin_manages_path'] or $this_page['module_name']) {
		$page_manages_path = $this_page;
	}
	$base_path = $this_page['full_path'];
}
$smarty->assign('breadcrumb', $breadcrumb);



if ($this_page) {
	$page = $this_page;
} elseif(isset($page_manages_path)) {
	$page = $page_manages_path;
}

if (isset($page)) {
	$page['content'] = $db->fetchPairs("SELECT name, value FROM site_pages_revisions_content WHERE revision_id=?", $page['revision_id']);
	$page['plugins'] = array_merge(
		$db->fetchAll("SELECT * FROM site_pages_revisions_plugins WHERE revision_id=?", $page['revision_id']),
		$db->fetchAll("SELECT * FROM site_templates_plugins WHERE template_id=?", $page['template_id'])
	);
}

/*
 * Get the navigation.  This is a recursive array of all the pages
 *
 */
$navigation = get_navigation($breadcrumb[0]['id'], '', 0);
function get_navigation($parent_id, $current_path, $level) {
	global $db, $site, $path, $page;
	$pages = $db->fetchAll("SELECT p.id, r.title, r.path, r.link FROM site_pages p LEFT JOIN site_pages_revisions r ON p.revision_id=r.id WHERE p.site_id=? AND p.parent_id=? AND active=1 ORDER BY sort", array($site['id'], $parent_id));
	for($i=0;$i<count($pages);$i++) {
		$pages[$i]['full_path'] =  $current_path . '/' . $pages[$i]['path'];
		if (isset($path[$level]) and $path[$level] == $pages[$i]['path']) {
			$pages[$i]['ancestor'] = 1;
		}
		if ($page['id'] == $pages[$i]['id']) {
			$pages[$i]['active'] = 1;
		}
		$pages[$i]['children'] = get_navigation($pages[$i]['id'], $pages[$i]['full_path'], $level+1);
	}
	return $pages;
}
$smarty->assign('navigation', $navigation);


/*
 * If we've got nothing in $page by now, then 404
 *
 */
if (!$page) {
	header("HTTP/1.0 404 Not Found"); 
	$smarty->display('404.tpl.html');
	exit;
}

/*
 * If $page has a link, redirect to it
 *
 */
if ($page['link']) {
	header("Location: {$page['link']}");
	exit;
}

/*
 * Run Plugins
 *
 */
$plugin_return = array();
$plugin_result = '';
foreach($page['plugins'] as $plugin) {
	if (file_exists($app_root . $plugin['file'])) {
		ob_start();
		$return = quarantined_include($app_root . $plugin['file'], $plugin['config']);
		if (is_array($return)) {
			$plugin_return = array_merge($plugin_return, $return);
		}
		$plugin_result .= ob_get_contents();
		ob_end_clean();
	}
}
$smarty->assign('plugin_return', $plugin_return);
$smarty->assign('plugin_result', $plugin_result);
function quarantined_include($file, $config) {
	$cwd = getcwd();
	chdir(dirname($file));
	return include $file;
	chdir($cwd);
}


/*
 * Assign standard smarty variables
 *
 */
$smarty->assign('title', $page['title']);
$smarty->assign('meta_description', $page['meta_description']);
$smarty->assign('meta_keywords', $page['meta_keywords']);

/*
 * Assign template variables
 *
 */
foreach($page['content'] as $key => $val) {
	$smarty->assign($key, $val);
}

/*
 * And output the template
 *
 */
if ($page['module_name']) {
	if (file_exists("{$app_root}{$site['home_dir']}/admin-custom/frontend/{$page['module_name']}/{$page['module_name']}.php")) {
		require "{$app_root}{$site['home_dir']}/admin-custom/frontend/{$page['module_name']}/{$page['module_name']}.php";
	} else {
		require "{$app_root}/admin/frontend/{$page['module_name']}/{$page['module_name']}.php";
	}
} else {
	$template = $db->fetchRow("SELECT * FROM site_templates WHERE id=?", $page['template_id']);
	$smarty->display("site/{$template['file']}");
}
